import requests
from lxml import etree
import re
from colorama import Fore


class WeiBo(object):
    #  初始化
    def __init__(self, kw: str):
        #  构造url
        self.url = f'https://s.weibo.com/user?q={kw}&Refer=weibo_user'
        #  请求头部信息
        self.headers = {
            #  火狐浏览器的User-Agent
            'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0',
        }
        #  初始化cookies , 以便后续使用
        self.cookies = {
            'SUB': '_2AkMo1O1Cf8PxqwJRmf4Xz2zqZYlxyQvEieKeiByZJRMxHRl-yT92qmkotRB6A1TDrlkrMWMI17PVpC9-Lh2GCSOd5fYJ',
            'SUBP': '0033WrSXqPxfM72-Ws9jqgMF55529P9D9WhRfNYbLbFaqU7CRCccb31Q',
            'SINAGLOBAL': '8901259828538.324.1602773634807',
            'ULV': '1602811873179:2:2:2:8290532350314.348.1602811872939:1602773635809',
            '_s_tentry': '-',
            'Apache': '8290532350314.348.1602811872939'
        }
        #  初始化session
        self.session = requests.session()
        self.get_info()

    #  获取用户的信息
    def get_info(self):
        #  用户个人信息字典
        user = {}
        #  异常捕获
        try:
            res = self.session.get(self.url, headers=self.headers)
        except Exception:
            raise
        if res.status_code == 200:
            text = res.text
            #  获取HTML内容 , 开始解析
            html = etree.HTML(text)
            #  获取所有的用户
            users_div = html.xpath('//*[@id="pl_user_feedList"]/div[position()<=3]')
            #  遍历所有的用户
            for index in range(len(users_div)):
                #  获取用户的个人信息首页链接
                user_href = users_div[index].xpath('./div[@class="info"]/div/a[@class="name"]/@href')[0]
                #  用户的位置
                location = users_div[index].xpath('./div[@class="info"]/p[1]/text()')[1].strip()
                user['Location'] = location
                #  用户的个人空间链接
                link = f"https:{user_href}?is_all=1"
                user['Link'] = link
                user_info = requests.get(link, headers=self.headers, cookies=self.cookies)
                if user_info.status_code == 200:
                    #  去掉多余的换行空格
                    user_content = user_info.text.strip()
                    #  解析HTML , 获取用户名 , 性别 , 年龄 , 地址 , 星座 , 粉丝量
                    user_name = re.search('((\w+)?[-]?[\u4e00-\u9fa5]+([\S-]+)?)', user_content).groups()[0].split('，')[
                        0]
                    if '的微博' in user_name:
                        user_name = user_name.split('的')[0]
                    user['Name'] = user_name
                    #  性别
                    try:
                        sex = '男' if re.search('W_icon icon_pf_((fe)?male)', user_content).groups()[0] == 'male' else '女'
                    except AttributeError:
                        sex = '暂无'
                    user['Sex'] = sex
                    #  可能用户没有设置年月日 , 捕获异常
                    try:
                        birth = list(re.search('(\d{4})年(\d{1,2})月(\d{1,2})日', user_content).groups())
                    except AttributeError:
                        birth = []
                        pass
                    date_format = f"{birth[0]}-{birth[1]}-{birth[2]}" if birth else '暂无'
                    user['Date of birth'] = date_format
                    #  星座
                    constellation = re.findall(r'S_ficon.*\\t([\u4e00-\u9fa5]+座).*', user_content)
                    #  如果constellation为空 , 赋值constellation = '暂无'
                    constellation = constellation[0] if constellation else '暂无'
                    user['Constellation'] = constellation
                    #  用户的粉丝量
                    fans = re.findall(r'strong class=.*>(\d+).*strong.*粉丝.*', user_content)[0]
                    user['Fans'] = fans
                    self.show_info(user, index)
                else:
                    print(f'请求失败 , 响应吗为{user_info.status_code}')
        else:
            print("Can't got any data from WeiBo !")

    #  显示用户信息
    def show_info(self, user, index):
        # 打印信息
        print(Fore.RED + f'''
        ♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂
        ♂   No.{index + 1}
        ♂      Name ➦ {user['Name']}
        ♂      Sex  ➦ {user['Sex']}
        ♂      Date of Birth ➦ {user['Date of birth']}
        ♂      Location ➦ {user['Location']}
        ♂      Constellation ➦ {user['Constellation']}
        ♂      Fans ➦ {user['Fans']}
        ♂      Link ➦ {user['Link']}
        ♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂♂
        ''')


#  主函数
def main():
    #  打印logo
    print(Fore.RED + '''
            oddddddddddddddddddddddddddd
            WMdcccccclxO0KKK0kdlcccccoMM
            WM.  .:xKMMMMMMMMMMWKd,   MM
            WM.'OMMMMMMMMMMMMMMMMMMNc.MM
            WMOMMMMMMMMMMMMMMMMMMMMMMXMM
            WMx0MMMX0KMMMMMMMMN0KWMMXdMM
            WM: 0olxo. ;kWMKl. ckolK.;MM
            WMc:KXMMMWKc'0M:,kNNMMXWolMM
            WMWMNkM;   oMXMXX.  .0NkMMMM
            WMMMMM00XKxXXOMkXx0NNXWMMMMM
            WMMNckMMMMMONMMMXKMMMMN,OMMM
            WMM. ;OKOl'.'xO: .;oO0l  NMM
            WMK,                    .0MM
            WM.,xlc::'.........:cloko.MM
            WM. cMMMMWd,.   .cKMMMM0 .MM
            WM.  WMMMMMMMMMMMMMMMMM: .MM
            WM.  .KMMMMMMMMMMMMMMWc  .MM
            WM.    ;0MMMMMMMMMMXl    .MM          
            WMl::::::OMMMKKWMMNc:::::lMM          
            xxxxxxxxxxxxxxxxxxxxxxxxxxxx
                                        Version 1.0
                                        Coded by BlackJack
            ''')
    while True:
        try:
            kw = input(Fore.RED + 'fsociety[ Enter Ctrl + D to exit ! ]>>> ')
        except (EOFError, KeyboardInterrupt):
            print('\nThanks for using ! Bro')
            break
        else:
            WeiBo(kw)


if __name__ == '__main__':
    main()
